﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Workflow;
using System.Web;
using MethodWorx.CMS.Providers;
using MethodWorx.CMS.Membership;

namespace MethodWorx.CMS.Web
{
    public class HttpWorkflowExecutionContext : IWorkflowExecutionContext
    {
        private Dictionary<string, object> cache = new Dictionary<string, object>();
        private HttpContext context;
        private Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

        public HttpWorkflowExecutionContext(HttpContext context, User user)
        {
            this.context = context;
            this.CurrentUser = user;
        }

        public ICmsDataProvider CmsDataProvider { get; set; }
        public User CurrentUser { get; private set; }

        #region IWorkflowExecutionContext Members

        public object GetWorkflowValue(string name)
        {
            if (this.cache.ContainsKey(name.ToLower()))
                return this.cache[name.ToLower()];
            else
            {
                var v = this.context.Request[name.ToLower()];
                if (v != null)
                {
                    this.cache.Add(name.ToLower(), v);
                    return v;
                }
            }
            return null;
        }

        public IEnumerable<string> GetWorkflowErrors(string name)
        {
            if (this.errors.ContainsKey(name.ToLower()))
                return this.errors[name.ToLower()];
            else
                return null;
        }

        public void AddWorkflowError(string name, string value)
        {
            if (!this.errors.ContainsKey(name.ToLower()))
                this.errors.Add(name.ToLower(), new List<string>());

            this.errors[name.ToLower()].Add(value);
        }

        public bool IsValid()
        {
            return !this.errors.Any();
        }

        #endregion

        public Dictionary<string, string> GetAllWorkflowValues()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var value in this.cache.Keys)
            {

                dict.Add(value, this.cache[value].ToString());
            }

            return dict;
        }

        public void AddWorkflowValue(string name, object value)
        {
            cache.Add(name.ToLower(), value);
        }


        public T GetService<T>()
        {
            return this.CmsDataProvider.GetService<T>();
        }
    }
}
